package com.lsp.server.user.service;

import com.lsp.server.user.mapper.AreaMapper;
import com.lsp.server.user.domain.po.AreaEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName AreaService
 * @Description TODO
 * @Author Mr Hao
 * @Date 2021/11/24 18:23
 */
@Service
public class AreaService {

    @Resource
    private AreaMapper areaMapper;

    private StringBuffer sb=null;

    public Object GetAreaDataJson() {
        //地区的全部数据
        List<AreaEntity> areas = areaMapper.queryAlLData();
        sb=new StringBuffer("[");
        //得到顶层节点   pid=0  [{北京 value  label     children:[]   children[{},{}]         },{上海},{河南}]

        //[{ label:'北京',value:123 ,children:[], },{tianj}]
        int count=0;
        for (int i = 0; i <areas.size() ; i++) {
            AreaEntity area = areas.get(i);
            if(area.getPid()!=null&&area.getPid()==0){
                count++;
                sb.append("{");
                //具体处理北京的数据
                sb.append("\"label\":\"").append(area.getName()).append("\",\"value\":").append(area.getId());
                getChildren(area.getId(),areas);
                sb.append("},");
            }
        }
        return sb.substring(0,sb.length()-1)+"]";
    }

    /*  { children:[]   }        */
    private void getChildren(Integer id,List<AreaEntity> allData){
        sb.append(",\"children\":[");
        /*    */
        int count=0;
        for (int i = 0; i <allData.size() ; i++) {
            AreaEntity area = allData.get(i);
            //
            if(area.getPid()!=null&&area.getPid().equals(id)){
                count++;
                sb.append("{");
                sb.append("\"label\":\"").append(area.getName()).append("\",\"value\":").append(area.getId());
                getChildren(area.getId(),allData);
                sb.append("},");
            }
        }
        if(count>0){
            sb.replace(sb.length()-1,sb.length(),"]");
        }else{
            sb.replace(sb.length()-13,sb.length(),"");
        }
    }
}
